package org.example.projecttwo.common.utils;

import org.example.projecttwo.entity.news.News;
import org.example.projecttwo.mapper.news.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component
public class NewsNoGenerator {

    private static NewsMapper newsMapper;
    private static final Lock LOCK = new ReentrantLock();
    private static final String PREFIX = "NEWS";
    private static final int DIGITS = 3;

    @Autowired
    public void setNewsMapper(NewsMapper mapper) {
        newsMapper = mapper;
    }

    /**
     * 生成格式为NEWS001、NEWS002的自增编号
     */
    public static String generateNewsNo() {
        LOCK.lock();
        try {
            // 查询当前最大编号
            String maxNewsNo = newsMapper.selectMaxNewsNo();

            if (maxNewsNo == null) {
                // 没有记录时从001开始
                return PREFIX + String.format("%0" + DIGITS + "d", 1);
            }

            // 提取数字部分并加1
            int num = Integer.parseInt(maxNewsNo.substring(PREFIX.length()));
            num++;

            // 格式化为3位数字（自动补零）
            return PREFIX + String.format("%0" + DIGITS + "d", num);
        } finally {
            LOCK.unlock();
        }
    }
}